package com.aqie.demo.npe;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author: aqie
 * @create: 2020-12-26 21:48
 **/
public class ForeachOptimize {
    private static Collection<Integer> left =
            Arrays.asList(1, 2, 3, 4);
    private static Collection<Integer> right =
            Arrays.asList(1, 2,3,4,5);

    private static void square(int value) {
        System.out.println(value * value);
    }

    private static void wrongIterator() {
        // 传统方式 - 迭代器
        /*for (Iterator<Integer> i = left.iterator(); i.hasNext(); ) {
            System.out.println(i.next());
        }*/

        // 嵌套迭代容易出现问题 错误写法
        /*for (Iterator<Integer> l = left.iterator(); l.hasNext(); ) {
            for (Iterator<Integer> r = right.iterator(); r.hasNext(); ) {
                System.out.println(l.next() * r.next());
            }
        }*/
        // 正确的用法, 嵌套迭代
        /*for (Iterator<Integer> l = left.iterator(); l.hasNext(); ) {
            Integer tmp = l.next();
            for (Iterator<Integer> r = right.iterator(); r.hasNext(); ) {
                System.out.println(tmp * r.next());
            }
        }*/
        /*for (Integer l : left) {
            for (Integer r : right) {
                System.out.println(l * r);
            }
        }*/


    }

    public static void main(String[] args) {
        // wrongIterator();
        // Java8 Iterable.forEach vs for-each
        /*for (Integer l : left) {
            square(l);
        }*/

        left.forEach(l -> square(l));
//        left.forEach(ForeachOptimize::square);
    }
}
